﻿#include "attendencewin.h"
#include "ui_attendencewin.h"
#include <QDateTime>
#include <QSqlQuery>
#include <QThread>
#include <opencv.hpp>
AttendenceWin::AttendenceWin(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::AttendenceWin)
{
    ui->setupUi(this);
    //初始化
    model.setTable("employee");
    m_tcpServer=new QTcpServer;
    m_tcpSocket=new QTcpSocket;
    connect(m_tcpServer,&QTcpServer::newConnection,this,&AttendenceWin::accept_client);
    m_tcpServer->listen(QHostAddress::Any,9999);

    //创建线程
    QThread* thread=new QThread();
    fobj.moveToThread(thread);
    thread->start();

    connect(this,&AttendenceWin::query,&fobj,&QFaceObject::face_qurrey);
    connect(&fobj,&QFaceObject::sendFaceid,this,&AttendenceWin::recv_faceid);
}

AttendenceWin::~AttendenceWin()
{
    delete ui;
}

void AttendenceWin::accept_client()
{
    m_tcpSocket=m_tcpServer->nextPendingConnection();
    connect(m_tcpSocket,&QTcpSocket::readyRead,this,&AttendenceWin::read_data);
}

void AttendenceWin::read_data(){
    //stream流绑定tcpsocket
    QDataStream stream(m_tcpSocket);
    //设置流版本
    stream.setVersion(QDataStream::Qt_5_14);

    if(bsize==0){
        //如果tcp读的字节数不足就返回
        if(m_tcpSocket->bytesAvailable()<(quint64)sizeof(bsize)){
            return;
        }
        stream>>bsize;
    }

    //如果小于就说明数据没读完,继续等待
    if(m_tcpSocket->bytesAvailable()<bsize){
        return;
    }
    QByteArray data;
    stream>>data;

    //把bsize归零，准备读下一次图片
    bsize=0;
    if(data.size()==0){
        return;
    }

    //把数据显示在图片上
    QPixmap pixmap;
    pixmap.loadFromData(data,"jpg");
    pixmap=pixmap.scaled(ui->userLabel->size());
    ui->userLabel->setPixmap(pixmap);

    //识别人脸
    cv::Mat faceImage;
    std::vector<uchar> decode;
    decode.resize(data.size());
    memcpy(decode.data(),data.data(),data.size());
    faceImage=cv::imdecode(decode,cv::IMREAD_COLOR);

    //这里查询消耗时间并且阻塞后续功能
    //使用多线程优化
    // int faceid=fobj.face_qurrey(faceImage);
    emit query(faceImage);
    // qDebug()<<faceid;

}

void AttendenceWin::recv_faceid(int faceid,float similarity)
{

    // qDebug()<<"faceid"<<faceid;
    //从数据库中查询faceid对应的个人信息
    if(faceid<0){
        QString sdmsg=QString("{\"employeeID\":\"\",\"name\":\"\",\"department\":\"\",\"time\":\"\" }");
         m_tcpSocket->write(sdmsg.toUtf8());
        qDebug()<<faceid;
        qDebug()<<"return 0";
        return;
    }
    //给模型设置过滤器
    model.setFilter(QString("faceId=%1").arg(faceid));
    //查询
    model.select();
    //判断是否查询到数据
    qDebug()<<"id";
    qDebug()<<model.rowCount();
    if(model.rowCount()==1){
        QSqlRecord record = model.record(0);
        ui->wokernumlab->setText(record.value("employeeID").toString());
        ui->namelab->setText(record.value("name").toString());
        ui->similaritylab->setText(QString::number(similarity, 'f', 6));
        ui->timelab->setText(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));

        QString sdmsg=QString("{\"employeeID\":\"%1\",\"name\":\"%2\",\"department\":\"%3\",\"time\":\"%4\"}")
                            .arg(record.value("employeeID").toString()).arg(record.value("name").toString())
                            .arg(record.value("department").toString())
                            .arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));

        QString insertSql = QString("insert into attendance(employeeID) values('%1')").arg(record.value("employeeID").toString());
        QSqlQuery query;
        if(!query.exec(insertSql)){
            QString sdmsg=QString("{\"employeeID\":\"\",\"name\":\"\",\"department\":\"\",\"time\":\"\" }");
            m_tcpSocket->write(sdmsg.toUtf8());
            return;
        }else{
            m_tcpSocket->write(sdmsg.toUtf8());
        }

    }
}


